phantom.injectJs('core.js');

var suite = new Suite(phantom.args[0]);

var fs = suite.fs;
var workingDir = suite.workingDir;

console.log('Working dir: ' + workingDir);

function cleanFolders() {

    try { fs.removeTree(suite.sourcePath); } catch (e) {}
    try { fs.removeTree(suite.compiledPath); } catch (e) {}
    fs.makeTree(suite.sourcePath);
    fs.makeTree(suite.compiledPath);

}

function clearPath(path) {
    return path.replace(workingDir, '').split('..').join('_').split('\\').join('_').split('/').join('_').split(':').join('_');
}

function scanDir(dir, pattern, recursive) {

    console.log('  Dir: ' + dir);

    var res = [];
    var list = fs.list(dir);

    forEach(list, function(file) {

        var path = dir + '/' + file;

        if (file == '.' || file == '..') return;

        if (fs.isDirectory(path)) {

            if (recursive) res = res.concat(scanDir(path, pattern, recursive));

        } else {

            if (file.match(pattern)) {
                console.log('    File: ' + file);
                res.push(path);
            } else {
                console.log('    Skip: ' + file);
            }

        }

    });

    return res;

}

function getScripts() {

    console.log('Including files');

    var files = [];

    files.push(suite.workingDir + '/qunit-coverage.js');
    files.push(suite.workingDir + '/qunit-jstestdriver.js');

    forEach(suite.config.includes, function(entry, key) {

        var originalPath = workingDir + entry.file;
        var newFile = clearPath(entry.file);
        var newPath = suite.sourcePath + '/' + newFile;

        if ('coverage' in entry && entry.coverage) {

            console.log('  Copy from: ' + originalPath);
            fs.copy(originalPath, newPath);
            files.push(newPath);

        } else {

            console.log('     Use at: ' + originalPath);
            files.push(originalPath);

        }

    });

    return files;

}

function getTests() {

    console.log('Searching for tests');

    var files = [];

    forEach(suite.config.testCases, function(suite) {

        var tests = scanDir(workingDir + suite.location, suite.pattern, suite.recursive);
        forEach(tests, function(test) {
            files.push(test);
        });

    });

    console.log('Included tests');
    forEach(files, function(file){
        console.log('  Test: ' + file);
    });

    return files;

}

function getScriptsHTML(scripts) {

    var scriptsHtml = [];
    forEach(scripts, function(script) {
        scriptsHtml.push('<script src="' + script.split('\\').join('\\\\') + '" type="text/javascript"></script>');
    });

    return scriptsHtml.join('\n');

}

function getHTML(scriptsHtml) {

    var testContent = fs.read(suite.runnerTemplate);
    return testContent.replace('<script id=\'includes\'></script>', scriptsHtml);

}

function writeHTML(html) {
    fs.write(suite.testRunnerSource, html, 'w');
}

try {

    cleanFolders();
    var scripts = getScripts();
    var tests = getTests();
    var scriptsHtml = getScriptsHTML([].concat(scripts, tests));
    var html = getHTML(scriptsHtml);
    writeHTML(html);

    phantom.exit();

} catch (e) {

    console.log('Critical error: ' + JSON.stringify(e));
    phantom.exit(1);

}

